import 'package:flutter/material.dart';

main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.teal, cardColor: Colors.orange),
      debugShowCheckedModeBanner: false,
      home: HYHomePage(),
    );
  }
}

class HYHomePage extends StatefulWidget {
  @override
  _HYHomePageState createState() => _HYHomePageState();
}

class _HYHomePageState extends State<HYHomePage> {
  ScrollController _controller = ScrollController(initialScrollOffset: 300);
  bool _isShowFloatingBtn = false;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      // print('监听到滚动...${_controller.offset}');
      setState(() {
        _isShowFloatingBtn = _controller.offset >= 1000;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    /**
     * 两种方式可以监听:
     *  controller:
     *    1.可以设置默认值
     *    2.监听滚动,也可以监听滚动位置
     *  NotificationListener:
     *    1.开始滚动和结束滚动
     */
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo'),
      ),
      body: NotificationListener(
        onNotification: (ScrollNotification notification) {
          if (notification is ScrollStartNotification) {
            print('开始滚动...');
          } else if (notification is ScrollUpdateNotification) {
            print(
                '正在滚动... 总滚动的距离:${notification.metrics.maxScrollExtent}, 当前滚动的位置:${notification.metrics.pixels}');
          } else if (notification is ScrollEndNotification) {
            print('结束滚动...');
          }
          return true;
        },
        child: ListView.builder(
          // scrollDirection: Axis.horizontal,
          // itemExtent: 400,

          itemBuilder: (BuildContext ctx, int index) => ListTile(
            leading: Icon(Icons.people),
            title: Text('联系人$index'),
          ),
          itemCount: 70,

          controller: _controller,
        ),
      ),
      floatingActionButton: _isShowFloatingBtn
          ? FloatingActionButton(
          child: Icon(Icons.arrow_upward),
          backgroundColor: Colors.teal,
          onPressed: () {
            _controller.animateTo(0,
                duration: Duration(seconds: 1), curve: Curves.easeIn);
          })
          : null,
    );
  }
}
